package com.example.capturetheflag.helper;

import java.util.Iterator;
import java.util.LinkedList;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class GameField extends Overlay {
	public LinkedList<GeoPoint> fieldPoints = new LinkedList<GeoPoint>();
	Path gameBorder;
	protected int pointsNum;
	private Paint paint;

	public GameField( int ilPkt ) {
		super();
		if(ilPkt<3) ilPkt=3;
		pointsNum = ilPkt;
		gameBorder = new Path();
		paint = new Paint();
		paint.setARGB(255, 255, 0, 0);
		paint.setStrokeWidth(3);
		paint.setStyle(Paint.Style.STROKE);
	}
	
	
	public void AddGeoPoint(GeoPoint gp)
	{
//		if(fieldPoints.size()>=pointsNum)
//		{
//			while(fieldPoints.size()>0) fieldPoints.removeFirst();
//			gameBorder.reset();
//		}
		fieldPoints.addLast(gp);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event, MapView mapView) 
	{
        if (event.getAction() == 1)
        {                
            GeoPoint p = mapView.getProjection().fromPixels( (int) event.getX(),(int) event.getY());
            AddGeoPoint(p);

            if(fieldPoints.size()>=pointsNum)
            	mapView.setClickable(false);
        }
		return super.onTouchEvent(event, mapView);
	}
	
	public GeoPoint getCenterOfField() 
	{
		int x1=0,x2=0,y1=0,y2=0, i=0;
		for(Iterator<GeoPoint> it = fieldPoints.iterator(); it.hasNext();)
		{
			GeoPoint gp = (GeoPoint)it.next();
			if(i==0)
			{
				x1 = x2 = gp.getLatitudeE6();
				y1 = y2 = gp.getLongitudeE6();
			}
			else
			{
				if(gp.getLatitudeE6()<x1)
					x1 = gp.getLatitudeE6();
				if(gp.getLatitudeE6()>x2)
					x2 = gp.getLatitudeE6();
				if(gp.getLongitudeE6()<y1)
					y1 = gp.getLongitudeE6();
				if(gp.getLongitudeE6()>y2)
					y2 = gp.getLongitudeE6();
			}
			i++;
		}
		int X, Y;
		X = (x2+x1)/2;
		Y = (y2+y1)/2;
		return new GeoPoint(X, Y);
	}


	@Override
	public void draw( Canvas canvas, MapView mapView, boolean shadow)
	{
		super.draw(canvas, mapView, shadow);
		
		gameBorder.reset();
		
		Projection pr = mapView.getProjection();
		
		int rozm = fieldPoints.size();
		int x=0, y=0;
		
		Point pt = new Point();
		if(rozm<2) return;
		int i=0;
		
		for(Iterator<GeoPoint> it = fieldPoints.iterator(); it.hasNext();)
		{
			GeoPoint gp = (GeoPoint)it.next();
			pr.toPixels(gp, pt);
			
			if(i==0)
			{
				gameBorder.moveTo(pt.x, pt.y);
				x = pt.x;
				y = pt.y;
			}
			else
			{
				gameBorder.lineTo(pt.x, pt.y);
				if(i==3)
					gameBorder.lineTo(x, y);
			}
			i++;
		}
		canvas.drawPath(gameBorder, paint);
	}
}
